package com.xyy.saas.payment.job.syncData;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.constants.Constants;
import com.xyy.saas.payment.service.JDPayService;
import com.xyy.saas.payment.trace.AlarmService;
import com.xyy.saas.payment.trace.DingTalkMessage;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Calendar;
import java.util.Date;

/**
 * 京东对账单下载
 * 每天早上8点，每隔10分钟执行一次
 */
@ElasticJobConf(name = "xyy.elastic.job.manage.jdCardPayBillJob", cron = "0 0/15 8 * * ?")
@Slf4j
public class JDPayBillJob implements SimpleJob {

    @Value("${checkBillSwitch:false}")
    private Boolean checkBillSwitch;

    @Autowired
    private JDPayService jdPayService;
    @Autowired
    private AlarmService alarmService;

    @Override
    public void execute(ShardingContext shardingContext) {
        try {
            if (!Boolean.parseBoolean(ApolloUtil.getProperty(Constants.APOLLO_KEY_ANALY_JDBILL, "true"))) {
                log.info("apollo配置不进行京东账单解析，跳过处理");
                return;
            }
            Calendar calendar = Calendar.getInstance();
            if (calendar.get(Calendar.HOUR_OF_DAY) == 8 && calendar.get(Calendar.MINUTE) == 0) {
                log.info("当前时间为：{}，不进行处理！", DateUtil.format(new Date(), DateUtil.DATEFORMATSECOND));
                return;
            }
            String logPrefix = "JDPayBillJob#execute";
            log.info("{} [jdPay]账单处理: JDPayBillJob#execute start", logPrefix);
            long start = System.currentTimeMillis();
            String msg = jdPayService.billDeal(logPrefix, "", false);
            if (checkBillSwitch) {
                String checkBillResult = jdPayService.checkBill("");
            }

            log.info("{} [jdPay]账单处理: JDPayBillJob#execute end，报送结果：{} , 耗时{}ms ", logPrefix, msg, System.currentTimeMillis() - start);
            if (StringUtils.isNotBlank(msg)) {

                DingTalkMessage talkMessage = DingTalkMessage.builder().type("京东支付").method("JDPayService.billDeal").msg(msg).param("").build();
                alarmService.alarm(talkMessage);
            }
        } catch (Exception e) {
            log.error("JDPayBillJob#execute error", e);

        }

    }

}
